﻿using System;
using System.Text;
using log4net;
using log4net.Config;
using System.Net;
using System.Net.Mail;
using Davian.Model;

namespace Davian.BLL
{
    class Mail
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Mail));
        private SysXml sysXml = null;
        private MailAccount mailAccount = null;

        public Mail()
        {
            sysXml = new SysXml();
            mailAccount = sysXml.ReadMailAccount();
        }

        public void Send(){
            try{
                String txtTo = "liying2010@huawei.com";
                String txtTitle = "Test Lycnsc";
                String txtContent = "Hello World !";
                log.Info("Start sending mail.");
                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(txtTo);
                mailMessage.From = new MailAddress(mailAccount.From);
                mailMessage.Subject = txtTitle;
                mailMessage.Body = txtContent;
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = Encoding.UTF8;
                mailMessage.Priority = MailPriority.Normal;

                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Credentials = new NetworkCredential(mailAccount.Username, mailAccount.Password);
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtpClient.Host = mailAccount.OutgoingHost;
                smtpClient.Port = mailAccount.OutgoingPort;
                smtpClient.EnableSsl = false;
                smtpClient.Send(mailMessage);
            }catch(Exception ex){
                log.Error("Sent mail failed.");
                log.Error(ex.ToString());
            }
            finally
            {
                log.Info("Sent mail successfully.");
            }
        }
    }
}
